package com.botann.projects.filter;

import com.botann.projects.base.LoggerIntf;
import com.botann.projects.model.RequestLog;
import com.botann.projects.service.AdminUserServiceIntf;
import com.botann.projects.base.LoggerIntf;
import com.botann.projects.model.RequestLog;
import com.botann.projects.service.AdminUserServiceIntf;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Enumeration;

/**
 * Charging
 * BaseInterceptor
 * Created by 刘山国 on 2018/11/21.
 * Copyright (c) 2017 伯坦科技. All rights reserved
 */
public abstract class BaseInterceptor extends HandlerInterceptorAdapter implements LoggerIntf {

    protected Logger logger = Logger.getLogger(loggerClass());

    @Autowired
    protected AdminUserServiceIntf service;

    protected void forward(HttpServletRequest request, HttpServletResponse response, String path) throws Exception {
        RequestDispatcher rd =request.getRequestDispatcher(path);
        rd.forward(request, response);
    }

    protected void generateRequestLog(HttpServletRequest request,Integer userId,boolean success, String info) {
        String uri = request.getRequestURI();
        // 记录请求日志
        RequestLog requestLog = new RequestLog();
        requestLog.setIp(getIpAddr(request));
        requestLog.setUrl(uri == null ? "" : uri);
        requestLog.setRequestTime(new Date());
        requestLog.setUserId(userId);
        requestLog.setSuccess(success);
        requestLog.setUser("");
        requestLog.setInfo(info);
        requestLog.setHard("");
        requestLog.setSoft("");
        requestLog.setParmas(getRequestParamsStr(request));
        requestLog.setCome(1);
        service.saveRequestLog(requestLog);
    }

    protected String getResolvdeUrl(HttpServletRequest request) {
        // 0. 请求url 在token验证前处理
        String uri = request.getRequestURI();
        String url = uri == null ? "" : uri;

        return url;
    }


    /**
     *
     * getRequestURL:(将HttpServletRequest转成URL参数字符串 ). <br/>
     *
     */
    protected String getRequestParamsStr(HttpServletRequest request) {

        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;
        @SuppressWarnings("unchecked")
        Enumeration<String> er = request.getParameterNames();
        while (er.hasMoreElements()) {
            String name =  er.nextElement();
            String value = request.getParameter(name);
            if (isFirst) {
                sb.append(name + "=" + value);
                isFirst = false;
            }
            else {
                if (value != null) {
                    sb.append("&" + name + "=" + value);
                }
                else {
                    sb.append("&" + name + "=");
                }
            }
        }
        return sb.toString();
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null) ip = "";
        return ip;
    }


    /**
     * 3种方式获取token
     * @param request HttpServletRequest
     * @return authToken
     */
    protected String extractAuthTokenFromRequest(HttpServletRequest request)
    {
        /* 1.Get token from header */
        String authToken = request.getHeader("X-Custom-Header");
        if (authToken == null) authToken = request.getHeader("token");
        if (authToken == null) authToken = request.getHeader("X-Token");

        /* 2. Get token form cookie*/
        if (authToken == null && request.getCookies() != null) {
            Cookie cookie = getCookie(request);
            if (cookie != null) return cookie.getValue();
        }

        /* 3. If token not found get it from request parameter */
        if (authToken == null) authToken = request.getParameter("token");
        if (authToken == null) authToken = request.getParameter("pxx");
        if (authToken == null) {
            logger.info("token 为 null");
        } else {
            logger.info("token");
            logger.info(authToken);
        }
        return authToken;
    }

    protected Cookie getCookie(HttpServletRequest request) {
        return getCookieWithName("pxx",request);
    }

    protected Cookie getCookieWithName(String cookieName, HttpServletRequest request) {
        Cookie aCookie = null;
        Cookie[] cookies = request.getCookies();
        if (cookies == null) return null;
        Long longTimestamp = 0L;
        for (Cookie cookie : cookies){
            if (cookie.getName().equals(cookieName)) {
                String [] values = cookie.getValue().split(":");
                if (values.length>1) {
                    Long timestamp = Long.parseLong(values[1]);
                    if (timestamp>longTimestamp) {
                        longTimestamp = timestamp;
                        aCookie = cookie;
                    }
                }
            }
        }
        return aCookie;
    }

}
